package com.credithc.signature.common.service.lanmao;

import com.alibaba.fastjson.JSONObject;
import com.credithc.signature.common.constant.SealConstant;
import com.credithc.signature.common.mapper.LanmaoPersonSealMapper;
import com.credithc.signature.common.mapper.SealInfoMapper;
import com.credithc.signature.common.po.LanmaoPersonSeal;
import com.credithc.signature.common.po.SealInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

/**
 * @author zhq
 * 懒猫注册相关业务
 */
@Service
@Slf4j
public class LanmaoRegisterService {
    @Value("${cat.sdk.customerNo:911101135769049507A}")
    private String customerNo;
    @Value("${cat.sdk.method.personRegister:/sign/register/personal/id}")
    private String personMethod;
    @Value("${cat.sdk.method.entRegister:/sign/register/enterprise/id}")
    private String entMethod;

    @Autowired
    private LanmaoSdkClient lanmaoSdkClient;

    @Autowired
    private LanmaoPersonSealMapper lanmaoPersonSealMapper;

    @Autowired
    private SealInfoMapper sealInfoMapper;

    @Autowired
    private LanmaoSignImageService lanmaoSignImageService;

    /**
     * 注册懒猫个人用户 入库并返回userid
     * @return
     * cardType枚举：
     * 0-居民身份证
     * 1-护照
     * B-港澳居民往来内地通行证
     * C-台湾居民来往大陆通行证
     * E-户口簿
     * F-临时居民身份证
     */
    public String registerPerson(String name,String cardId,String cardType) throws Exception {
      //  查库
        Example lpme = new Example(LanmaoPersonSeal.class);
        Example.Criteria lpmc = lpme.createCriteria();
        lpmc.andEqualTo("cardId",cardId);
        lpmc.andEqualTo("name",name);
        lpmc.andEqualTo("cardType",cardType);
        LanmaoPersonSeal lanmaoPersonSeal = lanmaoPersonSealMapper.selectOneByExample(lpme);
        if(lanmaoPersonSeal != null && StringUtils.isNotBlank(lanmaoPersonSeal.getUserId())){
            log.info("{}注册过懒猫用户 直接返回userId：{}",name,lanmaoPersonSeal.getUserId());
            return lanmaoPersonSeal.getUserId();
        }

        //2 注册

//        LanmaoSdkClient lanmaoSdkClient = new LanmaoSdkClient();
//        lanmaoSdkClient.setHost("http://10.150.30.56:8080/openapi/api/v1.0");
//        lanmaoSdkClient.setPryKey("MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANBl14vy6b5/bMz2mFvstUhtt/yW55wpy4sK3vNXJKsUbFj0ey6DxpCcHDd2Hzflw5e3XXpfJPxkAGs7ug7KmjuCsc71Jkhp6p/NsdyqM7D3BMpQ2958+PGbim+7iY6J8mIbmpbTPIFeVtZUFlzK/9h6DT5yARtby2FMSeV3ZPXXAgMBAAECgYEAv1aCTRA+5JUCRD21LdFrsJBseRHknVESfRsCENJV7G3X/OSbpN2Alo1+qr1ddGkU6FuHDDAHOWRnrg0siyAh8hE6IU5uqypw9+l1AHacAcYeA9DDBY9z7LxuWFdxZ53eb9LJZ1ekPpbNv4E3yi7Pht2X3oQG4Ay9+5ADlGnwFMECQQDx2LZdSLf2Arq7u8DDyerXukGo2HJC5YT450HiMuvJMzypL4IxRPuBSungM19XVcSsieTEWdJbgwHfsl2vRFY5AkEA3JgCR8eJTO8veqJsg/IaP+X3iHM8xT3mcqJGG97z9yCITHI4E5R8gfcm6duOR6p2LatkllVCNmzKKzrZZJ8sjwJBANyd3H3sQCRjCQUImSgBogF5Hzxvdowf49VK4Ib//Kdl3ghYFmPrkaK4O/ER6/83dloO0Gltpr9kGul9RIkFxcECQHux7U1ssSvnz1rX6zuNrXR5MnVcEQ6VKDzNi7yjJ3BC2MrtHU61a5/BBBwMVlsPVddEDVJTGp7EIBVfmXlX3DcCQQDuZvWkfs9OJfV8YxkkiRgEsxXy8zLVwdPhUeepCMyFryFBfDthtg42UHaT2pxxeuGH8KvrDkNg8TI3LG/YJmn7");
//        lanmaoSdkClient.init();
//        String customerNo = "911101135769049507A";
//        String personMethod = "/sign/register/personal/id";


        JSONObject head = new JSONObject();
        head.put("customerNo", customerNo);
        JSONObject body = new JSONObject();
        body.put("name", name);
        //默认申请证书
        body.put("applyCert", "1");
        JSONObject credential = new JSONObject();
        credential.put("identityType", cardType);
        credential.put("identity", cardId);
        body.put("credential", credential);
        JSONObject json = new JSONObject();
        json.put("head", head);
        json.put("body", body);
        JSONObject rspJson = lanmaoSdkClient.post(personMethod, json);
        log.info("{}注册成功，返回值为{}",name,rspJson.toJSONString());
        JSONObject rspBody = rspJson.getJSONObject("body");



        //入库
        lanmaoPersonSeal = new LanmaoPersonSeal();
        lanmaoPersonSeal.setCardId(cardId);
        lanmaoPersonSeal.setCardType(cardType);
        lanmaoPersonSeal.setName(name);
        lanmaoPersonSeal.setUserId(rspBody.getString("userId"));
        log.info("{}第一次注册 插入数据库",rspBody.getString("userId"));
        lanmaoPersonSealMapper.insert(lanmaoPersonSeal);

        return rspBody.getString("userId");
    }
    /**
     * 注册懒猫企业用户 入库并返回userid
//     * @param companyName  公司名称
//     * @param mobile        电话
//     * @param regCode  工商
//     * @param orgCode  组织    如果是三证合一，regCode/taxCode/orgCode三个填一样的值
//     * @param taxCode  税务
//     * @param legalPersonName  法人姓名
//     * @param cardId         法人证件号
//     * @param cardType        法人证件类型
//     * @param phone          联系电话（联系手机必填，为CA年检抽查时联系使用，只能为手机号码，不能为座机号码）
     * @return
     * @throws Exception
     */
    public String registerEnt(String sealCode) throws Exception {
        //查库
        SealInfo sealInfo = sealInfoMapper.selectBySealCode(sealCode);
        if (StringUtils.isNotBlank(sealInfo.getUserId())){
            log.info("sealCode为{}公章注册过懒猫 直接返回userid{}",sealCode,sealInfo.getUserId());
            return sealInfo.getUserId();
        }
        JSONObject json = new JSONObject();
        JSONObject head = new JSONObject();
        head.put("customerNo", customerNo);
        JSONObject body = new JSONObject();
        body.put("name", sealInfo.getSealName());
        body.put("mobile", sealInfo.getPhone());
        //默认申请证书
        body.put("applyCert", "1");
        JSONObject credential = new JSONObject();

        credential.put("regCode", sealInfo.getIdentificationNo());
        credential.put("orgCode", sealInfo.getIdentificationNo());
        credential.put("taxCode", sealInfo.getIdentificationNo());
        credential.put("legalPerson", sealInfo.getLegalPersonName());
        credential.put("legalPersonIdentity", sealInfo.getLegalPersonId());
        credential.put("legalPersonIdentityType",sealInfo.getLegalPersonCardType());
        credential.put("contactMobile", sealInfo.getContactPhone());
        body.put("credential", credential);
        json.put("head", head);
        json.put("body", body);
        JSONObject rspJson = lanmaoSdkClient.post(entMethod, json);
        JSONObject rspHead = rspJson.getJSONObject("head");
        String code = rspHead.getString("rspCode");
        if (!SealConstant.SUCCESS.equals(code)){
            log.error("{}公章注册失败{}",sealCode,rspHead.toString());
            throw  new Exception(rspHead.toString());
        }
        log.info("{}公章注册成功{}",sealCode,rspHead.toString());

        JSONObject rspBody = rspJson.getJSONObject("body");
        // 3 修改数据库 返回userid
        sealInfo.setUserId(rspBody.getString("userId"));
        sealInfoMapper.updateByPrimaryKey(sealInfo);
        log.info("更新对应数据 userId为{}",rspBody.getString("userId"));

        //4更新公章图片
        lanmaoSignImageService.updataSignImage(sealInfo);
        return rspBody.getString("userId");
    }


}
